package xj.model.uml;

import static xj.model.uml.UMLModelConstants.ROLE_TEMPLATE;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;

public class Classifier 
  extends NamedElement {

  public Classifier() {
    this(null);
  }

  public Classifier(String name) {
    super(name);
  }

  @Override
  public Object clone() throws CloneNotSupportedException {
    Classifier c = (Classifier) super.clone();
    c.templates = new ArrayList<TemplateParameter>();
    Iterator<TemplateParameter> iter = templates.iterator();
    while (iter.hasNext()) {
      TemplateParameter p = iter.next();
      c.addTemplate((TemplateParameter) p.clone());
    }
    return c;
  }

  public boolean hasTemplate() {
    return (templates != null && templates.size() > 0);
  }

  public String getTemplates() {
    return getTemplateString();
  }

  public void setTemplates(String s) {
    removeAllTemplates();
    if (s != null) {
      StringTokenizer st = new StringTokenizer(s, ", ");
      while (st.hasMoreTokens()) {
	String t = st.nextToken();
	addTemplate(new TemplateParameter(t));
      }
    }
  }

  public String getTemplateString() {
    StringBuilder sb = new StringBuilder();
    // sb.append('<');
    if (templates != null) {
      boolean first = true;
      Iterator<TemplateParameter> iter = templates.iterator();
      while (iter.hasNext()) {
	TemplateParameter p = iter.next();
	if (first) {
	  first = false;
	} else {
	  sb.append(", ");
	}
	sb.append(p.toString());
      }
    }
    // sb.append('>');
    return sb.toString();
  }

  public void addTemplate(TemplateParameter p) {
    if (p != null) {
      templates.add(p);
      addOwnedElement(p, ROLE_TEMPLATE);
    }
  }

  public void removeTemplate(TemplateParameter p) {
    if (p != null) {
      templates.remove(p);
      removeOwnedElement(p);
    }
  }

  public void setTemplates(List<TemplateParameter> params) {
    removeAllTemplates();
    if (params != null) {
      int n = params.size();
      if (n > 0) {
	for (int i = 0; i < n; i++) {
	  TemplateParameter p = params.get(i);
	  addTemplate(p);
	}
      }
    }
  }

  public void removeAllTemplates() {
    Iterator<TemplateParameter> iter = templates.iterator();
    while (iter.hasNext()) {
      TemplateParameter p = iter.next();
      removeOwnedElement(p);
      iter.remove();
    }
  }

  protected List<TemplateParameter> templates = new ArrayList<TemplateParameter>();

}
